<template>
  <view class="upload">
    <up-upload
      :fileList="fileList"
      @afterRead="afterRead"
      @delete="deletePic"
      name="1"
      :uploadIcon="uploadIcon"
      :width="maxCount == 1 ? modelWidth : modelWidth / 4"
      :height="maxCount == 1 ? '180' : modelWidth / 4"
      :maxCount="maxCount"
      autoUploadDriver="local"
      getVideoThumb
      :previewFullImage="true"
    >
      <view
        class="upload-icon"
        :style="{
          width: modelWidth,
        }"
      >
        <up-icon name="plus" color="#1d7cff" size="25px"></up-icon>
        <text>
          <slot name="text"></slot>
        </text>
      </view>
    </up-upload>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useVModel } from "@vueuse/core";
import { uploadIdCardFront, uploadIdCardBack, uploadExploration, uploadQualification, uploadCertificate } from "@/api/photo";

const props = defineProps({
  typeIndex: {
    type: String,
    default: "1" /*根据此参数判断当前属于哪一个上传模块，可逐个获取当前上传结果*/,
  },
  uploadType: {
    type: String,
    default: "certificate" /*上传类型：idcard_front, idcard_back, exploration, qualification, certificate*/,
  },
  maxCount: {
    type: Number,
    default: 1,
  },
  uploadIcon: {
    type: String,
    default: "camera-fill",
  },
  uploadMd5: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["update:uploadMd5", "unloadConfirm"]);
const uploadMd5 = useVModel(props, "uploadMd5", emit) as any;
const fileList = ref<any>([]);
const uploadList = ref<any>([]);
const modelWidth = ref<any>();
uni.getSystemInfo({
  success: (res) => {
    modelWidth.value = res.screenWidth - 40 + "px";
  },
});

const deletePic = (data: any) => {
  uploadList.value.splice(data.index, 1);
  let list = [] as any;
  for (let item of uploadList.value) {
    list.push(item?.md5);
  }
  uploadMd5.value = list?.length ? list.join(",") : null;
  fileList.value.splice(data.index, 1);
};

const afterRead = async (event: any) => {
  let list = [].concat(event.file) as any;
  let fileListLength = fileList.value.length;
  list.map((item: any) => {
    fileList.value.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < list.length; i++) {
    try {
      const result = await uploadFilePromise(list[i].url);
      let item = fileList.value[fileListLength];
      fileList.value.splice(fileListLength, 1, {
        ...item,
        status: "success",
        message: "",
        url: result,
      });
      
      // 更新uploadMd5值
      if (props.maxCount == 1) {
        uploadMd5.value = result;
      } else {
        uploadList.value.push({ md5: result, url: result });
        let urlList = [] as any;
        for (let item of uploadList.value) {
          urlList.push(item?.md5);
        }
        uploadMd5.value = urlList.join(",");
      }
      
      console.log('图片上传成功，URL:', result);
    } catch (error: any) {
      let item = fileList.value[fileListLength];
      fileList.value.splice(fileListLength, 1, {
        ...item,
        status: "failed",
        message: error.message || "上传失败",
      });
      uni.showToast({
        title: error.message || "上传失败",
        icon: "none",
      });
    }
    fileListLength++;
  }
};
const uploadFilePromise = async (url: any) => {
  try {
    console.log('开始上传文件:', url);
    console.log('上传类型:', props.uploadType);
    
    let result;
    
    // 根据上传类型调用相应的API
    switch (props.uploadType) {
      case 'idcard_front':
        console.log('调用身份证正面上传API');
        result = await uploadIdCardFront(url);
        break;
      case 'idcard_back':
        console.log('调用身份证反面上传API');
        result = await uploadIdCardBack(url);
        break;
      case 'exploration':
        console.log('调用探险信息上传API');
        result = await uploadExploration(url);
        break;
      case 'qualification':
        console.log('调用个人资质上传API');
        result = await uploadQualification(url);
        break;
      case 'certificate':
        console.log('调用证书上传API');
        result = await uploadCertificate(url);
        break;
      default:
        console.log('使用默认证书上传API');
        result = await uploadCertificate(url);
        break;
    }
    
    console.log('上传成功，返回结果:', result);
    
    return result;
  } catch (error: any) {
    console.error('上传失败:', error);
    console.error('错误详情:', error.message);
    throw error;
  }
};
</script>
<style lang="scss" scoped>
.upload {
  border: 2px dashed #0468ff;
  min-height: 120px;
  aspect-ratio: 16/9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-left: 5px;
  margin-left: -3px;
  .upload-icon {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    text {
      font-size: 14px;
      color: #7c838d;
      padding-top: 10px;
    }
  }
}
</style>
